<?php

namespace App\AdminModule\Presenters;

use \Nette\Application\UI\Form,
    \Nette\Utils\Image,
    \Nette\Utils\Strings,
    \Nette\Utils\Html,
    \Grido, 
    \Grido\Grid,
    App\Model\Dao\Banner,
    App\Model\Dao\BannerPosition;

/**
 * Banner presenter.
 */
class BannerPresenter extends BasePresenter {
 
  /** @var \Kdyby\Doctrine\EntityManager @inject */
  public $em;
  
  /**
   * Create component Banner form
   * @param String $name
   * @return \Nette\Application\UI\Form
   */
  public function createComponentBannerForm($name){
    $form = new Form();
    $bannerPositions = $this->getPositionArray();
    
    $selectArr = array();
    foreach($bannerPositions as $position){
      $selectArr[$position['id']] = $position['name'];
    }
    $form->addText('title', 'Název');
    $form->addUpload('image', 'Název');
    $form->addSelect('position', 'Pozice', $selectArr);
    $form->addText('text', 'Text');
    $form->addText('style', 'Style');
    $form->addText('link', 'Link');
    $form->addText('fromdate', 'Od');
    $form->addText('todate', 'Do');
    $form->addSubmit('send', 'Odeslat');
    $form->onSuccess[] = callback($this, 'bannerSuccess');
    
    return $form;
  }
  
  /**
   * Executiong banner form
   * @param Form $form
   */
  public function bannerSuccess($form){
    $values = $form->getValues();
    
    $banner = new Banner();
    if ($values['image']->name != "" && $values['image']->isImage()) {
      $path = $this->savePicture($values['image']);
      $banner->setImage($path);
    }
    
    $bannerPositionDao = $this->em->getDao(BannerPosition::getClassName());
    $bp = $bannerPositionDao->find($values['position']);
    
    $banner->setBannerposition($bp);
    $banner->setLink($values['link']);
    $banner->setStyle($values['style']);
    $banner->setTitle($values['title']);
    $banner->setText($values['text']);
    
    if($values['fromdate']){
      $banner->setFromdate(new \DateTime($values['fromdate']));
    }
    
    if($values['todate']){
      $banner->setTodate(new \DateTime($values['todate']));
    }

    $this->em->persist($banner);
    $this->em->flush();

    $this->flashMessage('Nový banner byl vložen', 'success');
    $this->redirect('Banner:default');
  }
  
  /**
   * Handle for delete banner
   * @param int $id
   */
  public function handleDeleteBanner($id){
    
    $bannerDao = $this->em->getDao(Banner::getClassName());
    $b = $bannerDao->find($id);
    
    // TODO remove all banner on position
    
    $this->em->remove($b);
    $this->em->flush();
    $this->redirect('Banner:default');
  }
  
  /**
   * Banner position form
   * @param String $name
   * @return \Nette\Application\UI\Form
   */
  public function createComponentBannerPositionForm($name){
    $form = new Form();
    $form->addText('name', 'Název')->addRule(Form::FILLED, 'Název musí být vyplněn');
    $form->addSubmit('send', 'Odeslat');
    $form->onSuccess[] = callback($this, 'bannerPositionSuccess');
    
    return $form;
  }
  
  /**
   * Executing banner position form 
   * @param type $form
   */
  public function bannerPositionSuccess($form){
    $values = $form->getValues();
      
    $bannerPosition = new BannerPosition();
    $bannerPosition->setName($values['name']);

    $this->em->persist($bannerPosition);
    $this->em->flush();

    $this->flashMessage('Nová pozice banneru byla vložena', 'success');
    $this->redirect('Banner:position');
  }
  
  /**
   * Handle for delete position
   * @param int $id
   */
  public function handleDeletePosition($id){
    
    $bannerPositionDao = $this->em->getDao(BannerPosition::getClassName());
    $bp = $bannerPositionDao->find($id);
    
    // TODO remove all banner on position
    
    $this->em->remove($bp);
    $this->em->flush();
    $this->redirect('Banner:position');
  }
  
  /**
   * Banner position grid component
   * @param String $name
   * @return \Grido\Grid
   */
  public function createComponentPositionGrid($name){
   
    $g = new Grid($this, $name);
    
// Grido data
    $g->model = $this->getPositionArray();    
    
    $g->addColumnText('id', 'ID')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('name', 'Název')
        ->setSortable()
        ->setFilterText();
   
    // Create delete button
    $g->addActionHref('delete', 'Smazat', 'deletePosition!')
      ->setIcon('remove')->setPrimaryKey('id');
    
    // Return grido
    $g->filterRenderType = Grido\Components\Filters\Filter::RENDER_INNER;
    $g->setExport();
    return $g;
  }
  
  /**
   * Banner grid
   * @param String $name
   * @return \Grido\Grid
   */
  public function createComponentBannerGrid($name){
   
    $g = new Grid($this, $name);
    
    $qb = $this->em->createQueryBuilder()
      ->addSelect('b.id AS id')
      ->addSelect('b.title AS title')
      ->from(Banner::getClassName(), ' b');
    
    $g->model =$qb->getQuery()->getArrayResult();  
    
    $g->addColumnText('id', 'ID')
        ->setSortable()
        ->setFilterText();
    $g->addColumnText('title', 'Název')
        ->setSortable()
        ->setFilterText();
   
    $g->addActionHref('delete', 'Smazat', 'deleteBanner!')
      ->setIcon('remove')->setPrimaryKey('id');
    
    $g->addActionHref('edit', 'Editovat', 'Banner:editBanner')
      ->setIcon('pencil')->setPrimaryKey('id');
    
    // Return grido
    $g->filterRenderType = Grido\Components\Filters\Filter::RENDER_INNER;
    $g->setExport();
    return $g;
  }
  
  /**
   * Positions
   * @return array
   */
  private function getPositionArray(){
    $qb = $this->em->createQueryBuilder()
      ->addSelect('bp.id AS id')
      ->addSelect('bp.name AS name')
      ->from(BannerPosition::getClassName(), ' bp');
    
    return $qb->getQuery()->getArrayResult();
  }
  
  /**
   * Save banner picture
   * @param String $picture
   * @return string
   */
  private function savePicture($picture){
    $name = $picture->getName();
    $temp = $picture->getTemporaryFile();
		$image = Image::fromFile($temp);
		$hash = Strings::random(10) . time();
		$path = ROOT_DIR . '/content/banners/' . $hash;
		mkdir($path);
		$image->save($path . '/' . $name);
    $filePath = $hash . '/' . $name;
		return $filePath;
  }
}
